package cn.edu.swu.miniwebsvr.handler;

import cn.edu.swu.miniwebsvr.core.Handler;
import cn.edu.swu.miniwebsvr.core.Parameter;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class TimeHandler implements Handler {

    @Override
    public void handle(Parameter request, OutputStream response) {
        PrintWriter writer = new PrintWriter(response);

        try {
            String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            // 构造完整的HTML内容
            String htmlContent = buildHtmlContent(currentTime, request);
            byte[] contentBytes = htmlContent.getBytes("UTF-8");

            // [学号/姓名] 构造完整的 HTTP 响应头和响应体
            writer.println("HTTP/1.1 200 OK");
            writer.println("Content-Type: text/html; charset=UTF-8");
            writer.println("Content-Length: " + contentBytes.length);
            writer.println("Connection: close");
            writer.println("Server: MiniWebSvr/1.0");
            writer.println("Cache-Control: no-cache, no-store, must-revalidate");
            writer.println("Pragma: no-cache");
            writer.println("Expires: 0");
            writer.println(); // 空行分隔头部和体部

            writer.print(htmlContent);
            writer.flush();

            System.out.println("TimeHandler: 返回当前时间 " + currentTime);

        } catch (Exception e) {
            // 如果发生异常，返回500错误
            sendErrorResponse(writer, 500, "Internal Server Error", "时间处理器发生错误: " + e.getMessage());
        }
    }

    /**
     * 构建HTML内容
     */
    private String buildHtmlContent(String currentTime, Parameter request) {
        StringBuilder html = new StringBuilder();

        html.append("<!DOCTYPE html>");
        html.append("<html lang=\"zh-CN\">");
        html.append("<head>");
        html.append("    <meta charset=\"UTF-8\">");
        html.append("    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">");
        html.append("    <title>服务器时间 - MiniWebSvr</title>");
        html.append("    <style>");
        html.append("        body {");
        html.append("            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;");
        html.append("            margin: 0;");
        html.append("            padding: 20px;");
        html.append("            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);");
        html.append("            min-height: 100vh;");
        html.append("            display: flex;");
        html.append("            align-items: center;");
        html.append("            justify-content: center;");
        html.append("        }");
        html.append("        .container {");
        html.append("            background: white;");
        html.append("            padding: 40px;");
        html.append("            border-radius: 15px;");
        html.append("            box-shadow: 0 10px 30px rgba(0,0,0,0.2);");
        html.append("            text-align: center;");
        html.append("            max-width: 500px;");
        html.append("            width: 100%;");
        html.append("        }");
        html.append("        h1 {");
        html.append("            color: #333;");
        html.append("            margin-bottom: 30px;");
        html.append("            font-size: 2em;");
        html.append("        }");
        html.append("        .time-display {");
        html.append("            font-size: 2.5em;");
        html.append("            color: #667eea;");
        html.append("            font-weight: bold;");
        html.append("            margin: 20px 0;");
        html.append("            padding: 20px;");
        html.append("            background: #f8f9fa;");
        html.append("            border-radius: 10px;");
        html.append("            border: 2px solid #e9ecef;");
        html.append("        }");
        html.append("        .info {");
        html.append("            margin-top: 30px;");
        html.append("            padding-top: 20px;");
        html.append("            border-top: 1px solid #eee;");
        html.append("            color: #666;");
        html.append("            font-size: 0.9em;");
        html.append("        }");
        html.append("        .refresh-btn {");
        html.append("            background: #667eea;");
        html.append("            color: white;");
        html.append("            border: none;");
        html.append("            padding: 12px 24px;");
        html.append("            border-radius: 6px;");
        html.append("            cursor: pointer;");
        html.append("            font-size: 1em;");
        html.append("            margin-top: 20px;");
        html.append("            transition: background 0.3s;");
        html.append("        }");
        html.append("        .refresh-btn:hover {");
        html.append("            background: #5a6fd8;");
        html.append("        }");
        html.append("    </style>");
        html.append("</head>");
        html.append("<body>");
        html.append("    <div class=\"container\">");
        html.append("        <h1>🕐 服务器当前时间</h1>");
        html.append("        <div class=\"time-display\">").append(currentTime).append("</div>");
        html.append("        <button class=\"refresh-btn\" onclick=\"location.reload()\">🔄 刷新时间</button>");
        html.append("        <div class=\"info\">");
        html.append("            <p>请求方法: ").append(request.getMethod()).append("</p>");
        html.append("            <p>请求路径: ").append(request.getUrl()).append("</p>");
        html.append("            <p>处理器: TimeHandler</p>");
        html.append("        </div>");
        html.append("    </div>");
        html.append("</body>");
        html.append("</html>");

        return html.toString();
    }

    /**
     * 发送错误响应
     */
    private void sendErrorResponse(PrintWriter writer, int statusCode, String statusText, String message) {
        try {
            writer.println("HTTP/1.1 " + statusCode + " " + statusText);
            writer.println("Content-Type: text/html; charset=UTF-8");
            writer.println("Connection: close");
            writer.println();
            writer.println("<!DOCTYPE html>");
            writer.println("<html>");
            writer.println("<head><title>" + statusCode + " " + statusText + "</title></head>");
            writer.println("<body>");
            writer.println("<h1>" + statusCode + " " + statusText + "</h1>");
            writer.println("<p>" + message + "</p>");
            writer.println("</body>");
            writer.println("</html>");
            writer.flush();
        } catch (Exception ex) {
            // 忽略错误响应发送失败的情况
        }
    }
}